using System;
using System.Diagnostics;

using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;


namespace SBPweb.Logging
{
    /// <summary>
    /// EntLib base class for custom trace listeners.
    /// </summary>
    public abstract class EntLibTraceListener : CustomTraceListener
    {
        /// <summary>
        /// Registers this instance as uninitialized trace listener.
        /// </summary>
        /// <remarks>
        /// The uninitialized trace listeners can become initialized by calling <see cref="LogManager.Initialize()"/>.
        /// This method supports the EntLib infrastructure.
        /// </remarks>
        public EntLibTraceListener()
            : base()
        {
            LogManager.AddUninitializedListener(this);
        }

        /// <summary>
        /// Removes this instance from the list of initialized trace listeners.
        /// </summary>
        /// <remarks>
        /// This method supports the EntLib infrastructure.
        /// </remarks>
        ~EntLibTraceListener()
        {
            LogManager.RemoveInitializedListener(this);
        }

        /// <summary>
        /// Called by <see cref="LogManager"></see> to initialize related objects.
        /// </summary>
        /// <remarks>
        /// By calling this the <see cref="LogManager"/> transforms this instance to be initialized and removes it from the collection
        /// of uninitialized listeners and adds it to the collection of initialized trace listeners.
        /// The initialization process can be started by calling <see cref="LogManager.Initialize()"/>.
        /// This method supports the EntLib infrastructure.
        /// </remarks>
        protected internal abstract void InitializeRelatedObjects();

        /// <summary>
        /// Delivers the trace data to the underlying layer and formats it if possible by using the associated formatter instance.
        /// </summary>
        /// <param name="EventCache">The context information provided by <see cref="System.Diagnostics"/>.</param>
        /// <param name="Source">The name of the trace source that delivered the trace data.</param>
        /// <param name="EventType">The type of event.</param>
        /// <param name="ID">The id of the event.</param>
        /// <param name="Data">The data to trace.</param>
        public override void TraceData(TraceEventCache EventCache, String Source, TraceEventType EventType, int ID, object Data)
        {
            if (Data is LogEntry && this.Formatter != null)
            {
                WriteLine(this.Formatter.Format(Data as LogEntry));
            }
            else
            {
                WriteLine(Data.ToString());
            }
        }
    }
}
